#!/bin/bash

# 脚本信息
echo
echo "* Swap一键添加/修改脚本 V1.2"
echo "*    blog.zeruns.com"
echo

# 检查是否以root身份运行
if [ "$(id -u)" != "0" ]; then
    echo "请以root身份运行此脚本"
    exit 1
fi

# 检查系统类型并安装bc命令（如果需要）
function check_system() {
    if [[ -f /etc/redhat-release ]]; then
        release="centos"
    elif grep -q -E -i "debian" /etc/issue; then
        release="debian"
    elif grep -q -E -i "ubuntu" /etc/issue; then
        release="ubuntu"
    elif grep -q -E -i "centos|red hat|redhat" /etc/issue; then
        release="centos"
    elif grep -q -E -i "debian" /proc/version; then
        release="debian"
    elif grep -q -E -i "ubuntu" /proc/version; then
        release="ubuntu"
    elif grep -q -E -i "centos|red hat|redhat" /proc/version; then
        release="centos"
    fi

    case $release in
        ubuntu|debian)
            if ! [ -x "$(command -v bc)" ]; then
                apt-get -y install bc
            fi;;
        centos)
            if ! [ -x "$(command -v bc)" ]; then
                yum -y install bc
            fi;;
    esac
}

# 检查是否是OpenVZ虚拟化
function check_ovz() {
    if [[ -d "/proc/vz" ]]; then
        echo "OVZ虚拟化不支持设置SWAP"
        exit 1
    fi
}

# 主菜单
function main() {
    totalswap=$(free -m | grep "Swap:" | awk '{print$2}')
    echo "当前SWAP：$totalswap MB"
    echo
    echo "1、设置SWAP大小"
    echo "2、SWAP参数优化"
    echo "3、退出"
    echo -n "请输入："
    read -e choice
    case $choice in
        1)
            add_swap;;
        2)
            optimize_swap;;
        3)
            exit;;
        *)
            echo "输入错误，请重新输入"
            main;;
    esac
}

# 添加SWAP
function add_swap() {
    echo "请输入设置Swap大小(单位Mb)"
    read -e swap_size
    file="/swapfile"

    # 移除所有现有的SWAP文件和配置
    swapoff -a
    sed -i '/swapfile/d' /etc/fstab
    rm -f /swapfile

    swap_size=$(expr $swap_size + 1) 

    # 创建新的SWAP文件
    dd if=/dev/zero of=$file bs=1MiB count=$swap_size
    chmod 600 $file
    mkswap $file
    swapon $file
    echo "$file none swap sw 0 0" | tee -a /etc/fstab
    main
}


# 优化SWAP参数
function optimize_swap() {
    echo "正在优化..."
    echo
    echo "当前vm.swappiness：$(cat /proc/sys/vm/swappiness)"
    echo "当前vm.vfs_cache_pressure：$(cat /proc/sys/vm/vfs_cache_pressure)"
    sysctl vm.swappiness=10
    sysctl vm.vfs_cache_pressure=50
    echo "vm.swappiness=10" >> /etc/sysctl.conf
    echo "vm.vfs_cache_pressure=50" >> /etc/sysctl.conf
    echo "优化完成"
    main
}

# 执行检查
check_system
check_ovz
main
